<template>
  <div class="dynamic_form_item" >
    <div class="dynamic_form_select_all" v-if="props.question.type === 'selectAll'">
      <a-select v-model:value="gatherInputName" :options="props.question.options" @change="gatherChange"></a-select>
      <a-form-item :name="props.question.key">
        <a-input v-model:value="props.question.value" :disabled="props.question.disabled" :placeholder="props.question.placeholder || '请输入'" allowClear />
      </a-form-item>
    </div>
    <template v-else>
        <a-form-item :name="props.question.key" :class="{ 'icons_btn': props.question.state.labelIcon }">
          <template v-slot:label >
            <label for="">{{ props.question.label }}</label>
            <span class="item_icons"  v-if="props.question.state.labelIcon">
              <i class="iconfont icon-add-circle" v-if="props.question.state.addIcon" @click="addItam"></i>
              <i class="iconfont icon-minus-circle" v-else @click="clearItem()"></i>
            </span>
            <a-tooltip class="item_tooltip"  v-if="props.question.state.tipText" :key="props.question.label" :title="props.question.state.tipText" >
              <i class="iconfont" :style="{ marginLeft: '8px' }" :class="props.question.state.tipIconClassName"></i>
            </a-tooltip>
          </template>
          <template v-if="props.question.type === 'static' || props.config?.isView">
            <span class="" :style="{color:props.question.state?.color?.[props.question.value]}">{{ props.question.value }}</span>
            <span v-if="props.question.state.addonAfter">{{ props.question.state.addonAfter.text }}</span>
          </template>
          <template v-else-if="props.question.type === 'number'">
            <a-input-number v-model:value="props.question.value" :disabled="props.question.disabled" :placeholder="props.question.placeholder || '请输入'" allowClear :max="props.question.state.maxlength || null" :min="props.question.state.minLength || 0"  @blur="inputBlur" @pressEnter="pressEnter" v-numberInput :id="'dynamic_rule_'+props.question.key" style="width:100%">
              <template #addonAfter v-if="props.question.state.addonAfter">
                <a-form-item-rest>
                  <a-select v-model:value="props.question.state.extendParams[props.question.state.addonAfter.key]" :disabled="props.question.state.addonAfter.disabled" v-if="props.question.state.addonAfter.tagType === 'select'">
                    <a-select-option v-for="item in props.question.state.addonAfter.options" :key="item.value" :value="item.value">
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                  <a-input v-else v-model:value="props.question.state.extendParams[props.question.state.addonAfter.key]" :disabled="props.question.state.addonAfter.disabled" :placeholder="props.question.state.addonAfter.placeholder || '请输入'" allowClear  />
                </a-form-item-rest>
              </template> 
            </a-input-number>
          </template>
          <template v-else-if="props.question.type === 'password'">
            <a-input-password  v-model:value="props.question.value" :disabled="props.question.disabled" :placeholder="props.question.placeholder || '请输入'" :autocomplete="props.question.state.autocomplete || 'new-password'"  :id="'dynamic_rule_'+props.question.key" @pressEnter="pressEnter"/>
          </template>
          <template v-else-if="props.question.type === 'textarea'">
            <a-textarea v-model:value="props.question.value" :disabled="props.question.disabled" :placeholder="props.question.placeholder || '请输入'"  :maxlength="props.question.state.maxlength || 9999" :auto-size="{ minRows: 3, maxRows: 3 }" :id="'dynamic_rule_'+props.question.key" @blur="inputBlur"/>
          </template>
          <template v-else>
            <a-input v-model:value="props.question.value" :disabled="props.question.disabled" :placeholder="props.question.placeholder || '请输入'" allowClear  :maxlength="props.question.state.maxlength || null"  @blur="inputBlur" :id="'dynamic_rule_'+props.question.key" @pressEnter="pressEnter">
              <template #addonAfter v-if="props.question.state.addonAfter">
                <a-form-item-rest>
                  <a-select v-model:value="props.question.state.extendParams[props.question.state.addonAfter.key]" :disabled="props.question.state.addonAfter.disabled" v-if="props.question.state.addonAfter.tagType === 'select'">
                    <a-select-option v-for="item in props.question.state.addonAfter.options" :key="item.value" :value="item.value">
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                  <a-input v-else v-model:value="props.question.state.extendParams[props.question.state.addonAfter.key]" :disabled="props.question.state.addonAfter.disabled" :placeholder="props.question.state.addonAfter.placeholder || '请输入'" allowClear  />
                </a-form-item-rest>
              </template> 
              <template #suffix>
                <a-tooltip :title="props.question.state.suffixText" v-if="props.question.state.suffixIcon">
                 <i class="iconfont"  :class="props.question.state.suffixIcon" :style="props.question.state.suffixIconStyle"></i>
                </a-tooltip>
                <div v-else-if="props.question.state.suffixText" :style="props.question.state.suffixTextStyle">{{props.question.state.suffixText}}</div>
              </template>
            </a-input>
          </template>
        </a-form-item>
      </template>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, onUnmounted, ref, watch } from 'vue';
import { QuestionBase } from '../../../question-base';
import { formInfoStore } from '@/store/modules/form';
import { INPUTSERVE } from '@/mixins/subject/subject-types';
import { Subscription } from 'rxjs';
import { filter } from 'rxjs/operators';
import { INFOSERVE } from '@/mixins/subject/subject-types';
import localDictionary from '@/filters/dictionary';
//subject变量
let $subscribeSub: Subscription;

const { proxy }: any = getCurrentInstance();
let props = defineProps<{ question: QuestionBase<any>; formData: any ;config?:any;}>();
const emit = defineEmits(['update:formData','parentServe','autoSearch']);

let gatherInputName: any = ref('');
watch(
  () => props.question.value,
  (val) => {
    emit('update:formData', val);
  },
  { flush: 'sync' }
);

onMounted(() => {
  subWatch();
  init();
});

//解绑
onUnmounted(() => {
  if ($subscribeSub != undefined) {
    $subscribeSub.unsubscribe();
  }
});

//回车事件
const pressEnter = ()=>{
  //自动搜索
  if(props.config.style === 'table-form'){
    emit('parentServe', { key: 'autoSearch' });
  }
}
//下拉选字段
const gatherChange = (val: any) => {
  props.question.asKey = val;
  // gatherInputName = val;
};

//初始化后缀的对应的值
const initAddonAfterLabel = () => {
  if (props.question.state.extendParams[props.question.state.addonAfter.key] !== undefined) {
    let obj: any = props.question.state.addonAfter.options.find((res) => res.value === props.question.state.extendParams[props.question.state.addonAfter.key]);
    console.log('aaaa', props.question);
    props.question.state.addonAfter.text = obj ? obj.label : '';
  }
};
//离开焦点事件
const inputBlur = ()=>{
  if(  typeof props.question.value === 'string'){
    props.question.value = props.question.value.trim(); //去掉首尾空格
  }
  console.log('啥意思',props.question.value);
  proxy.$NotificationFormSub.pushParams({
    key: INPUTSERVE,
    value: {
      key: props.question.key,
      value: props.question.value,
      name: props.question.state.name
    }
  });
}

const init = () => {
  if (props.question.type === 'selectAll') {
    gatherInputName.value = props.question.options[0].value;
  }
  //组合类型
  if (props.question.state.addonAfter) {
    if (props.question.state.addonAfter.type === 'dictionary') {
      const formStore = formInfoStore();
      let dictionary = formStore.getDictionary;
      let dicObj: any = dictionary[props.question.state.addonAfter.filterName] || localDictionary[props.question.state.addonAfter.filterName];
      let arr: any = [];
      for (const key in dicObj) {
        if (dicObj.hasOwnProperty(+key)) {
          arr.push({
            label: dicObj[key],
            value: props.question.state.addonAfter?.valueType === 'string' ? key + '' : +key
          });
        }
      }
      props.question.state.addonAfter.options = arr;
      //初始化后缀的对应的值
      initAddonAfterLabel();
    } else if (props.question.state.addonAfter.url) {
      let params = Object.assign({}, props.question.state.addonAfter.params || {});
      proxy.$Http.api(props.question.state.addonAfter.url, params, props.question.state.addonAfter.protType ? props.question.state.addonAfter.protType : 'get').then((res) => {
        if (res) {
          // // 递归children
          const state = props.question.state.addonAfter;
          function reData(list: any[]) {
            if (!list) {
              return [];
            }
            return list.map((data: any) => {
              const item: any = { ...data, label: data[state.nameKey], value: data[state.nameValue] + '' };
              if (data[state.nameChildren] && data[state.nameChildren].length > 0) {
                item.children = reData(data[state.nameChildren]);
              }
              return item;
            });
          }
          props.question.state.addonAfter.options = reData(res.data);
          //初始化后缀的对应的值
          initAddonAfterLabel();
        }
      });
    }
  }
};

//监听动态表单数据完成
const subWatch = () => {
  $subscribeSub = proxy.$NotificationFormSub
    .getParams()
    .pipe(filter((res: any) => res !== 0))
    .subscribe((item: any) => {
      try {
        if (item.key === INFOSERVE) {
          //数据都全部都到了
          init();
        }
      } catch (error) {}
    });
};

//找到确实顺序的数字
const autoMissSort = (questions: any, addName = '') => {
  var array: any = questions.filter((res) => res.key.includes(addName)).map((res) => +res.key.split(addName)[1]);

  // 数组排序
  array.sort(function (a, b) {
    return a - b;
  });

  // 查找缺失的数字
  var missingNumbers = [];
  for (var i = 1; i < array.length; i++) {
    var diff = array[i] - array[i - 1] - 1;
    if (diff > 0) {
      for (var j = 1; j <= diff; j++) {
        missingNumbers.push(array[i - 1] + j);
      }
    }
  }
  return missingNumbers.length ? missingNumbers[0] : '';
};

//新增
const addItam = () => {
  const formStore = formInfoStore();
  console.log('准备添加了');
  let arr: any = [];
  if (!props.question.state.indexItem) {
    props.question.state.indexItem = 0;
  }
  if (props.question.state.type === 'layer') {
    let miseeIndex = autoMissSort(formStore.getLayerQuestions, props.question.state.addName);
    var index = formStore.getLayerQuestions.findIndex(function (obj) {
      return obj.key === props.question.key + (miseeIndex ? miseeIndex - 1 : props.question.state.indexItem ? props.question.state.indexItem : '');
    });
    arr = [...formStore.getLayerQuestions];
    if (!miseeIndex) {
      props.question.state.indexItem++;
    }
    arr.splice(index + 1, 0, props.question.state.addItem(miseeIndex ? miseeIndex : props.question.state.indexItem));
    formStore.setLayerQuestions(arr);
  } else {
    let miseeIndex = autoMissSort(formStore.getLayerQuestions, props.question.state.addName);
    var index = formStore.getQuestions.findIndex(function (obj) {
      return obj.key === props.question.key + (miseeIndex ? miseeIndex - 1 : props.question.state.indexItem ? props.question.state.indexItem : '');
    });
    arr = [...formStore.getQuestions];
    if (!miseeIndex) {
      props.question.state.indexItem++;
    }
    arr.splice(index + 1, 0, props.question.state.addItem(miseeIndex ? miseeIndex : props.question.state.indexItem));
    formStore.setQuestions(arr);
  }
  setTimeout(() => {
    emit('parentServe', { key: 'initVerify' });
  });
};
//删除
const clearItem = () => {
  const formStore = formInfoStore();
  if (props.question.state.type === 'layer') {
    formStore.deleteLayerQuestions(props.question);
  } else {
    formStore.deleteQuestions(props.question);
  }
};
</script>

<style lang="less" scoped>
@import url('./input-item.component.less');
</style>
